package com.gxa.logistics.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.gxa.logistics.common.base.RespResult;
import com.gxa.logistics.common.util.JwtUtil;
import com.gxa.logistics.domain.dto.UserDTO;
import com.gxa.logistics.domain.entity.Menu;
import com.gxa.logistics.domain.entity.User;
import com.gxa.logistics.service.EmployeeService;
import com.gxa.logistics.service.RoleService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "用户登录")
@RestController
@RequestMapping("/auth")
@Slf4j
public class LoginController {

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private RoleService roleService;

    private LineCaptcha lineCaptcha;

    private Logger logger = LoggerFactory.getLogger(LoginController.class);

    /**
     * 实现登录逻辑
     */
    @ApiOperation(value = "登录", notes = "登录")
    @PostMapping("/login")
    public RespResult<UserDTO> login(@RequestBody @ApiParam(name = "loginMsg",value = "输入登录信息") @Validated UserDTO userDTO) {
        String username = userDTO.getUsername();
        String password = userDTO.getPassword();
        String imgText = userDTO.getImgText();
        logger.info("username:{}", username);
        logger.info("password:{}", password);
        logger.info("登录验证码:{}", lineCaptcha.getCode());

        // 验证码校验
        if (!imgText.equals(lineCaptcha.getCode())) {
            return RespResult.error(400, "验证码错误");
        }

        // 用户名校验
        User user = employeeService.findByUsername(username);
        if (user == null) {
            return RespResult.error(404, "该用户不存在");
        }

        //状态校验
        if(user.getStatus() == 0){
            return RespResult.error(400,"此用户已被冻结");
        }

        //密码校验
        if(!user.getPassword().equals(password)){
            return RespResult.error(400,"密码错误");
        }

        //设置token
        String token = JwtUtil.generateToken(userDTO);
        userDTO.setToken(token);

        String role = userDTO.getRole();

        List<Menu> roleMenus = roleService.getRoleMenus(role);

        userDTO.setMenus(roleMenus);

        return RespResult.success(userDTO);
    }

    @GetMapping("/getCode")
    public RespResult<String> getCode(){
        //随机生成四位验证码
        RandomGenerator randomGenerator = new RandomGenerator("0123456789",4);
        //定义显示图片的大小
        lineCaptcha = CaptchaUtil.createLineCaptcha(100,30);

        lineCaptcha.setGenerator(randomGenerator);
        String base64 = lineCaptcha.getImageBase64Data();
        logger.info("生成的验证码:{}", lineCaptcha.getCode());
        return RespResult.success(base64);
    }
}
